package com.syezon.wifikey.speed;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Method;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.Random;

/**
 * 网络工具类
 */
public class NetInfoUtils {

    private static final String TAG = "NetInfoUtils";
    //没有网络连接
    public static final int NETWORN_NONE = 0;
    //wifi连接
    public static final int NETWORN_WIFI = 1;
    //手机网络数据连接类型
    public static final int NETWORN_2G = 2;
    public static final int NETWORN_3G = 3;
    public static final int NETWORN_4G = 4;
    public static final int NETWORN_5G = 5;
    public static final int NETWORN_MOBILE = 6;

    /**
     * 获取网络类型
     */
    public static String getNetName(Context context) {
        int type = getNetworkState(context);
        if (type == NETWORN_WIFI) {
            return getConnectWifiSsid(context);
        } else if (type == NETWORN_2G) {
            return DeviceInfoUtils.getIsp();
        } else if (type == NETWORN_3G) {
            return DeviceInfoUtils.getIsp();
        } else if (type == NETWORN_4G) {
            return DeviceInfoUtils.getIsp();
        } else if (type == NETWORN_5G) {
            return DeviceInfoUtils.getIsp();
        } else if (type == NETWORN_NONE) {
            return "无网络连接";
        } else {
            return "";
        }
    }

    /**
     * 获取网络类型
     */
    public static String getNetType(Context context) {
        int type = getNetworkState(context);
        if (type == NETWORN_WIFI) {
            return "WiFi";
        } else if (type == NETWORN_2G) {
            return "2G";
        } else if (type == NETWORN_3G) {
            return "3G";
        } else if (type == NETWORN_4G) {
            return "4G";
        } else if (type == NETWORN_5G) {
            return "5G";
        } else if (type == NETWORN_NONE) {
            return "无网络连接";
        } else {
            return "";
        }
    }

    /**
     * 获取当前网络连接类型
     */
    public static int getNetworkState(Context context) {
        //获取系统的网络服务
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //如果当前没有网络
        if (null == connManager)
            return NETWORN_NONE;

        //获取当前网络类型，如果为空，返回无网络
        NetworkInfo activeNetInfo = connManager.getActiveNetworkInfo();
        if (activeNetInfo == null || !activeNetInfo.isAvailable()) {
            return NETWORN_NONE;
        }

        // 判断是不是连接的是不是wifi
        NetworkInfo info = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (null != info) {
            NetworkInfo.State state = info.getState();
            if (null != state)
                if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                    return NETWORN_WIFI;
                }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            try {
                ServiceState serviceState = telephonyManager.getServiceState();
                Method hwOwnMethod = ServiceState.class.getMethod("getHwNetworkType");
                hwOwnMethod.setAccessible(true);
                int result = (int) hwOwnMethod.invoke(serviceState);
                if (result == 20) {
                    return NETWORN_5G;
                }
            } catch (Exception e) {
            }
            try {
                int networkType = telephonyManager.getNetworkType();
                if (networkType == TelephonyManager.NETWORK_TYPE_NR) {// 对应的20 只有依赖为android 10.0才有此属性
                    return NETWORN_5G;
                }
            } catch (Exception e) {
            }
        }
        // 如果不是wifi，则判断当前连接的是运营商的哪种网络2g、3g、4g等
        NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (null != networkInfo) {
            NetworkInfo.State state = networkInfo.getState();
            String strSubTypeName = networkInfo.getSubtypeName();
            if (null != state)
                if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                    switch (activeNetInfo.getSubtype()) {
                        //如果是2g类型
                        case TelephonyManager.NETWORK_TYPE_GPRS: // 联通2g
                        case TelephonyManager.NETWORK_TYPE_CDMA: // 电信2g
                        case TelephonyManager.NETWORK_TYPE_EDGE: // 移动2g
                        case TelephonyManager.NETWORK_TYPE_1xRTT:
                        case TelephonyManager.NETWORK_TYPE_IDEN:
                            return NETWORN_2G;
                        //如果是3g类型
                        case TelephonyManager.NETWORK_TYPE_EVDO_A: // 电信3g
                        case TelephonyManager.NETWORK_TYPE_UMTS:
                        case TelephonyManager.NETWORK_TYPE_EVDO_0:
                        case TelephonyManager.NETWORK_TYPE_HSDPA:
                        case TelephonyManager.NETWORK_TYPE_HSUPA:
                        case TelephonyManager.NETWORK_TYPE_HSPA:
                        case TelephonyManager.NETWORK_TYPE_EVDO_B:
                        case TelephonyManager.NETWORK_TYPE_EHRPD:
                        case TelephonyManager.NETWORK_TYPE_HSPAP:
                            return NETWORN_3G;
                        //如果是4g类型
                        case TelephonyManager.NETWORK_TYPE_LTE:
                            return NETWORN_4G;
                        case TelephonyManager.NETWORK_TYPE_NR:
                            return NETWORN_5G;
                        default:
                            //中国移动 联通 电信 三种3G制式
                            if (strSubTypeName.equalsIgnoreCase("TD-SCDMA") || strSubTypeName.equalsIgnoreCase("WCDMA") || strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                                return NETWORN_3G;
                            } else {
                                return NETWORN_MOBILE;
                            }
                    }
                }
        }
        return NETWORN_NONE;
    }

    /**
     * @return 获取wifi dns
     */
    public static String getDns(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        DhcpInfo di = wifiManager.getDhcpInfo();
        return int2ip(di.dns1);
    }

    /**
     * @return 获取wifi网关地址
     */
    public static String getGateWay(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        DhcpInfo di = wifiManager.getDhcpInfo();
        int gateWayIp = di.gateway;
        return int2ip(gateWayIp);//网关地址
    }

    /**
     * @return 获取wifi网关地址
     */
    public static String getLocaleIp(Context context) {
        String result = "unknown";
        try {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            DhcpInfo di = wifiManager.getDhcpInfo();
            int gateWayIp = di.ipAddress;
            result = int2ip(gateWayIp);//ip地址
        } catch (Exception e) {

        }
        return result;
    }

    /**
     * @return 获取wifi子网掩码地址
     */
    public static String getNetMask(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        DhcpInfo di = wifiManager.getDhcpInfo();
        int netMaskIp = di.netmask;
        return int2ip(netMaskIp);//子网掩码地址
    }

    /**
     * int值转换为ip地址
     */
    public static String int2ip(int paramInt) {
        return (paramInt & 0xFF) + "." + (0xFF & paramInt >> 8) + "." + (0xFF & paramInt >> 16) + "."
                + (0xFF & paramInt >> 24);
    }

    /**
     * 获取连接wifi的名字
     */
    public static String getConnectWifiSsid(Context context) {
        String ssid = "";
        try {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifiManager.getConnectionInfo();
            ssid = info.getSSID();
            if (!TextUtils.isEmpty(ssid)) {
                ssid = ssid.replaceAll("\"", "");
            }
        } catch (Exception e) {
        }
        return ssid;
    }

    /**
     * 获取连接wifi的MacAddress
     */
    public static String getConnectWifiMac(Context context) {
        String mac = "";
        try {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//        int wifiState = wifiManager.getWifiState();
            WifiInfo info = wifiManager.getConnectionInfo();
            mac = info.getMacAddress();
        } catch (Exception e) {

        }
        return mac;
    }

    public static String getMac(Context context) {
        String mac = "";
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            mac = getMacDefault(context);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            mac = getMacAddress();
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mac = getMacFromHardware();
        }
        return mac;
    }

    /**
     * Android 6.0 之前（不包括6.0）获取mac地址
     * 必须的权限 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
     *
     * @param context * @return
     */
    private static String getMacDefault(Context context) {
        String mac = "";
        if (context == null) {
            return mac;
        }
        WifiManager wifi = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = null;
        try {
            info = wifi.getConnectionInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (info == null) {
            return null;
        }
        mac = info.getMacAddress();
        if (!TextUtils.isEmpty(mac)) {
            mac = mac.toUpperCase(Locale.ENGLISH);
        }
        return mac;
    }

    /**
     * Android 6.0-Android 7.0 获取mac地址
     */
    private static String getMacAddress() {
        String macSerial = null;
        String str = "";

        try {
            Process pp = Runtime.getRuntime().exec("cat/sys/class/net/wlan0/address");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            while (null != str) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();//去空格
                    break;
                }
            }
        } catch (IOException ex) {
            // 赋予默认值
            ex.printStackTrace();
        }

        return macSerial;
    }

    /**
     * Android 7.0之后获取Mac地址
     * 遍历循环所有的网络接口，找到接口是 wlan0
     * 必须的权限 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
     *
     * @return
     */
    private static String getMacFromHardware() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            List<NetworkInterface> all = Collections.list(networkInterfaces);
            for (NetworkInterface nif : all) {
                if (!nif.getName().equals("wlan0")) {
                    continue;
                }
                byte macBytes[] = nif.getHardwareAddress();
                if (macBytes == null) return "";
                StringBuilder res1 = new StringBuilder();
                for (Byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }
                if (!TextUtils.isEmpty(res1)) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 随机返回测网络延时用的域名
     */
    public static String getDomainName() {
        String[] domainNames = new String[]{"www.baidu.com", "www.qq.com", "www.163.com", "www.taobao.com", "www.tmall.com", "www.sohu.com"
                , "www.alipay.com", "www.netease.com", "www.zhibu.com", "www.csdn.net", "www.bing.com", "weibo.com", "www.hao123.com", "www.jd.com"
                , "www.ifeng.com", "www.youku.com", "www.1688.com"};
        Random random = new Random();
        int index = random.nextInt(domainNames.length);
        return domainNames[index];
    }
}
